package com.hsy.linemoney.modules.tender;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPGsonUtil;
import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.deparse.dpframe.tools.utils.DPUnitUtil;
import com.deparse.dpframe.ui.android.widget.adapter.DPBaseAdapter;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.BidService;
import com.hsy.linemoney.apiservice.CalculateService;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.CurrencyService;
import com.hsy.linemoney.modules.common.CommonBaseFragment;
import com.hsy.linemoney.modules.tender.activity.TenderStep1Activity;
import com.hsy.linemoney.utils.CommonUtils;

import java.util.List;

/**
 * Created by Administrator on 2016/6/23.
 */
public class TenderFragment extends CommonBaseFragment {
    private TextView select_finish, from_currency_spinner, to_currency_spinner, today_rate;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ListView listView;
    private TextView footerView;

    private List<String> listData;
    private LayoutInflater inflater;
    private BidListAdapter bidListAdapter;

    private CurrencyService currencyService = new CurrencyService();
    private BidService bidService = new BidService();
    private CalculateService calculateService = new CalculateService();

    private int leftWhich = -1, rightWhich = -1;
    private CurrencyService.CurrencyListResult mCurrencyListResult;
    private int firstVisibleItem = -1, visibleItemCount = -1;

    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_tender;
    }

    private SwipeRefreshLayout.OnRefreshListener listener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            bidService.getFromCurrencyToCurrencyOrder(mCurrencyListResult.getCurrency().get(leftWhich).getCurrencyCd(), mCurrencyListResult.getCurrency().get(rightWhich).getCurrencyCd(), new Callback<BidService.FromCurrencyToCurrencyOrderResult>() {
                @Override
                public void onSuccess(int what, BidService.FromCurrencyToCurrencyOrderResult result) {
                    bidListAdapter = new BidListAdapter(getAttchedActivity(), result.getValue());
                    listView.setAdapter(bidListAdapter);
                    swipeRefreshLayout.setRefreshing(false);
                    DPLogUtil.d("onRefresh onSuccess");
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {
                    showToast(R.string.txt_refresh_failed);
                    swipeRefreshLayout.setRefreshing(false);
                    DPLogUtil.d("onRefresh onError");
                }
            }, true);
        }
    };

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        showProgressDialog(getAttchedActivity());

        inflater = LayoutInflater.from(getAttchedActivity());
        select_finish = F(R.id.select_finish);
        from_currency_spinner = F(R.id.from_currency_spinner);
        to_currency_spinner = F(R.id.to_currency_spinner);
        swipeRefreshLayout = F(R.id.swip_refresh_layout);
        listView = F(R.id.listView);
        today_rate = F(R.id.today_rate);

        footerView = new TextView(getAttchedActivity());
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DPUnitUtil.dip2px(getAttchedActivity(), 40));
        footerView.setLayoutParams(params);
        listView.addFooterView(footerView);
        swipeRefreshLayout.setOnRefreshListener(listener);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                TenderFragment.this.firstVisibleItem = firstVisibleItem;
                TenderFragment.this.visibleItemCount = visibleItemCount;
                if (firstVisibleItem + visibleItemCount == totalItemCount && null != listView.getChildAt(listView.getChildCount())
                        && listView.getChildAt(listView.getChildCount()).getBottom() >= listView.getHeight()) {
                    footerView.setText(R.string.txt_loading_data);
                    sendEmptyMessageDelayed(0, 500);
                }
            }
        });

        currencyService.getCurrency(new Callback<CurrencyService.CurrencyListResult>() {
            @Override
            public void onSuccess(int what, CurrencyService.CurrencyListResult result) {
                TenderFragment.this.mCurrencyListResult = result;

                from_currency_spinner.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showListDialog(mCurrencyListResult.getCurrencyNameArray(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                from_currency_spinner.setText(mCurrencyListResult.getCurrencyNameArray()[which]);
                                dialog.dismiss();
                                leftWhich = which;
                                onCurrencySelected();
                            }
                        });
                    }
                });
                to_currency_spinner.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showListDialog(mCurrencyListResult.getCurrencyNameArray(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                to_currency_spinner.setText(mCurrencyListResult.getCurrencyNameArray()[which]);
                                dialog.dismiss();
                                rightWhich = which;
                                onCurrencySelected();
                            }
                        });
                    }
                });
                if (result.getCurrency().size() > 1) {
                    leftWhich = 1;
                    rightWhich = 0;
                    from_currency_spinner.setText(result.getCurrency().get(leftWhich).getDescription());
                    to_currency_spinner.setText(result.getCurrency().get(rightWhich).getDescription());
                    calculateService.calculate("USD", "CNY", "1", "0", "ServiceType_101", "0", new Callback<CalculateService.CalculateResult>() {
                        @Override
                        public void onSuccess(int what, CalculateService.CalculateResult result) {
                            today_rate.setText(result.getData().getLmData().getLinemoneyRate());
                            hideProgressDialog();
                        }

                        @Override
                        public void onError(int what, int type, String msg, Exception e) {
                            hideProgressDialog();
                        }
                    });
                    bidService.getFromCurrencyToCurrencyOrder(mCurrencyListResult.getCurrency().get(leftWhich).getCurrencyCd(), mCurrencyListResult.getCurrency().get(rightWhich).getCurrencyCd(), new Callback<BidService.FromCurrencyToCurrencyOrderResult>() {
                        @Override
                        public void onSuccess(int what, BidService.FromCurrencyToCurrencyOrderResult result) {
                            bidListAdapter = new BidListAdapter(getAttchedActivity(), result.getValue());
                            listView.setAdapter(bidListAdapter);
                            hideProgressDialog();
                            DPLogUtil.d("getFromCurrencyToCurrencyOrder:onSuccess");
                        }

                        @Override
                        public void onError(int what, int type, String msg, Exception e) {
                            hideProgressDialog();
                            DPLogUtil.d("getFromCurrencyToCurrencyOrder:onError");
                        }
                    });
                } else {
                    hideProgressDialog();
                }
            }

            @Override
            public void onError(int what, int type, String msg, Exception e) {
                hideProgressDialog();
            }
        });
    }

    private void onCurrencySelected() {
        if (leftWhich >= 0 && rightWhich >= 0 && leftWhich != rightWhich) {
            bidService.getFromCurrencyToCurrencyOrder(mCurrencyListResult.getCurrency().get(leftWhich).getCurrencyCd(), mCurrencyListResult.getCurrency().get(rightWhich).getCurrencyCd(), new Callback<BidService.FromCurrencyToCurrencyOrderResult>() {
                @Override
                public void onSuccess(int what, BidService.FromCurrencyToCurrencyOrderResult result) {
                    bidListAdapter = new BidListAdapter(getAttchedActivity(), result.getValue());
                    listView.setAdapter(bidListAdapter);
                    hideProgressDialog();
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {
                    hideProgressDialog();
                }
            }, true);
        }
    }

    private void showListDialog(String[] items, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder dialog = null;
        dialog = new AlertDialog.Builder(getContext()).setItems(items, listener);
        dialog.show();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onHandleMessage(Message msg) {
        if (0 == msg.what) {
            boolean a = false;
            if (a) {
                bidService.getFromCurrencyToCurrencyOrder(mCurrencyListResult.getCurrency().get(leftWhich).getCurrencyCd(), mCurrencyListResult.getCurrency().get(rightWhich).getCurrencyCd(), new Callback<BidService.FromCurrencyToCurrencyOrderResult>() {
                    @Override
                    public void onSuccess(int what, BidService.FromCurrencyToCurrencyOrderResult result) {
                        bidListAdapter = new BidListAdapter(getAttchedActivity(), result.getValue());
                        listView.setAdapter(bidListAdapter);
                    }

                    @Override
                    public void onError(int what, int type, String msg, Exception e) {

                    }
                });
            } else {
                footerView.setText(R.string.txt_no_more_data);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        listener.onRefresh();
    }

    @Override
    public void onFragmentUpdate() {
    }

    private class BidListAdapter extends DPBaseAdapter<BidService.FromCurrencyToCurrencyOrderResult.Value> {


        public BidListAdapter(Context context) {
            super(context);
        }

        public BidListAdapter(Context context, List<BidService.FromCurrencyToCurrencyOrderResult.Value> data) {
            super(context, data);
        }

        @Override
        public CommonBaseViewHolder<BidService.FromCurrencyToCurrencyOrderResult.Value> getHolder(int i) {
            return new ViewHoler();
        }

        private class ViewHoler extends CommonBaseViewHolder<BidService.FromCurrencyToCurrencyOrderResult.Value> implements View.OnClickListener {

            protected TextView orderSn;
            protected TextView orderTime;
            protected TextView orderMoney;
            protected TextView orderDuration;
            protected TextView orderRate;
            private BidService.FromCurrencyToCurrencyOrderResult.Value data;

            @Override
            public View create(int i) {
                View rootView = inflater.inflate(R.layout.item_tender_list, null);
                initView(rootView);
                return rootView;
            }

            @Override
            public void update(int i, BidService.FromCurrencyToCurrencyOrderResult.Value value) {
                data = value;
                orderSn.setText(getString(R.string.txt_order_sn, value.getOrderId()));
                orderTime.setText(value.getOrderTime());
                orderMoney.setText(value.getFromAmount());
                orderDuration.setText(value.getServiceTypeDesc());
                orderRate.setText(value.getFxRate());
            }

            private void initView(View rootView) {
                orderSn = (TextView) rootView.findViewById(R.id.order_sn);
                orderTime = (TextView) rootView.findViewById(R.id.order_time);
                orderMoney = (TextView) rootView.findViewById(R.id.order_money);
                orderDuration = (TextView) rootView.findViewById(R.id.order_duration);
                orderRate = (TextView) rootView.findViewById(R.id.order_rate);
                rootView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                startActivity(TenderStep1Activity.class, DPGsonUtil.toJson(data));
            }
        }
    }
}
